﻿using Microsoft.Azure.Cosmos.Table;
using Report.WebApi.Interfaces;
using Report.WebApi.Models;
using Report.WebApi.Models.ResponseModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToolManager.Entities;
using ToolManager.IService;
using Newtonsoft.Json;
using DataWasher.WebApi.Repositories;

namespace Report.WebApi.Services
{

    /// <summary>
    /// 维修类别费用
    /// </summary>
    public class QueryZZService : QueryService, IQueryZZService
    {
        private readonly IStorageService _storageService;
        private readonly ISysDomainRepository _repository;
        public QueryZZService(IStorageService storageService, ISysDomainRepository repository) : base(repository)
        {
            _storageService = storageService;
            _repository = repository;
        }

        public async Task<List<ZZResponse>> GetHomePageData(QueryDomainRequestModel request)
        {
            var response = new List<ZZResponse>();
            ZZResponse res = null;
            var thisData = new List<BusinessDataEntity>();
            var regionData = new List<BusinessDataEntity>();


            var requestModel = new QueryRequestModel()
            {
                Language = request.Language,
                DomainId = request.DomainNextId,
                QueryByMonth = request.QueryByMonth,
                QueryByCustom = request.QueryByCustom,
                QueryByYear = request.QueryByYear,
                QueryHomePage = request.QueryHomePage,
                QueryMntanCategory = request.QueryMntanCategory,
                QueryMonth = request.QueryMonth,
                QueryOrderByDesc = request.QueryOrderByDesc,
                QueryPriority = request.QueryPriority,
                QueryStatus = request.QueryStatus,
                QueryStore = request.QueryStore,
                QueryYear = request.QueryYear,
                StartTime = request.StartTime,
                EndTime = request.EndTime,
                OwnerId = request.OwnerId,
                QueryByQuarter = request.QueryByQuarter,
                QueryQuarter = request.QueryQuarter
            };
            try
            {
                //组装查询条件
                var thisYear = await GetMonthsThisYear(requestModel);
                var filter = await ParamBuilder(requestModel, thisYear);
                var query = new TableQuery<BusinessDataEntity>().Where(filter);
                var queryData = await _storageService.GetBusData("Businessdata", query);

                if (_connectionStrings.isDebug == 0)
                {
                    var domainIds = await GetDomainIds(requestModel);
                    queryData = queryData.Where(x => domainIds.Contains(x.DomainId)).ToList();
                }

                if (request.QueryByYear || request.QueryHomePage)
                    thisData = queryData.Where(x => x.AddDateYM >= thisYear.QueryBegin && x.AddDateYM <= thisYear.QueryEnd).ToList();

                if (request.QueryByMonth || request.QueryByCustom || request.QueryByQuarter)
                    thisData = queryData.Where(x => x.AddDate >= thisYear.QueryBegin && x.AddDate <= thisYear.QueryEnd).ToList();

                //获取区域分组
                var domainModellst = new List<DomainModel>();
                if (!string.IsNullOrEmpty(request.OwnerId))
                    domainModellst = await _repository.GetDomainList(request.OwnerId, "[dbo].[DGDomainNx]", 1);
                if (!string.IsNullOrEmpty(request.DomainNextId))
                    domainModellst = await _repository.GetDomainList(request.DomainNextId, "[dbo].[DGDomainNx]", 0);
                if (!string.IsNullOrEmpty(request.DomainPreId))
                {
                    domainModellst = await _repository.GetDomainList(request.DomainPreId, "[dbo].[DGDomainPre]", 0);
                    if (domainModellst.Count == 1)
                    {
                        domainModellst = await _repository.GetDomainList(domainModellst.FirstOrDefault().ParentDomainId, "[dbo].[DGDomainNx]", 0);
                    }

                }
                //根据区域分组计算费用
                domainModellst.ForEach(m =>
                {
                    res = new ZZResponse();
                    res.Category = m.DomainName;
                    res.DomainNextId = m.DomainId;
                    res.DomainPreId = m.ParentDomainId;
                    res.Count = thisData.Where(ite => m.DomainIds.Contains(ite.DomainId)).Sum(m => decimal.Parse(m.Settlement) == 0 ? decimal.Parse(m.Cost) : decimal.Parse(m.Settlement));
                    response.Add(res);
                });
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return response;
        }

        public async override Task<string> ParamBuilder(QueryRequestModel request, YearMonthModel filterModel)
        {
            var partitionKey = DateTime.Now.ToString("yyyyMMdd");
            var filterSB = new StringBuilder();
            filterSB.Append($"(PartitionKey eq '{partitionKey}')");
            filterSB.Append(" and ");

            filterSB.Append($"(AddDateYear eq {filterModel.Year})");
            filterSB.Append(" and ");

            #region 条件组合
            filterSB.Append($"(Language eq {request.Language})");

            if (!string.IsNullOrEmpty(request.QueryStore))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(TagName eq '{request.QueryStore}')");
            }

            if (!string.IsNullOrEmpty(request.QueryStatus))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntStatus eq '{request.QueryStatus}')");
            }

            if (!string.IsNullOrEmpty(request.QueryPriority))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(Priority eq '{request.QueryPriority}')");
            }
            if (!string.IsNullOrEmpty(request.QueryMntanCategory))
            {
                filterSB.Append(" and ");
                filterSB.Append($"(MntCategory2 eq '{request.QueryMntanCategory}')");
            }
            #endregion
            return filterSB.ToString();
        }




    }
}


